import { Subject } from "rxjs";
import * as tslib_1 from 'tslib';

export class SettingsService {
  private notify$ = new Subject();
  private _app;
  private _user;
  private _layout;
  private _system;
  private _token;

  LAYOUT = 'layout';
  USER = 'user';
  APP = 'app';
  SYS = 'system';
  TOKEN = 'token';

  private get(key) {
    return JSON.parse(localStorage.getItem(key) || 'null') || null;
  }

  private set(key, value) {
    localStorage.setItem(key, JSON.stringify(value));
  }

  // 页面布局
  get layout() {
    if (!this._layout) {
      this._layout = tslib_1.__assign({fixed: true, collapsed: false}, this.get(this.LAYOUT));
    }
    return this._layout;
  }

  setLayout(name: string | Layout, value?: any) {
    if (typeof name === 'string') {
      this.layout[name] = value; // 这样写能获取初始值
    } else {
      this._layout = name;
    }
    this.set(this.LAYOUT, this._layout);
    this.notify$.next({type: 'layout', name, value});
    return true;
  }

  // 应用信息
  get app() {
    if (!this._app) {
      this._app = tslib_1.__assign({}, this.get(this.APP));
      this.set(this.APP, this._app);
    }
    return this._app;
  }

  setApp(value: any) {
    this._app = value;
    this.set(this.APP, value);
  }

  // 用户信息
  get user() {
    if (!this._user) {
      this._user = tslib_1.__assign({}, this.get(this.USER));
      this.set(this.USER, this._user);
    }
    return this._user;
  }

  setUser(value: any) {
    this._user = value;
    this.set(this.USER, value);
  }

  clearAll() {
    localStorage.removeItem(this.USER);
    localStorage.removeItem(this.APP);
    localStorage.removeItem(this.LAYOUT);
  }

  get notify() {
    return this.notify$.asObservable();
  }
}

export interface Layout {
  [key: string]: any;
  collapsed: boolean;
}